
#import "Asset.h"

@implementation Asset

+ (NSArray *)fileTypes {
    // Subclasses should override this.
    return nil;
}

- initWithURL:(NSURL *)newURL {
    self = [super init];
    if (self) {
        [self setURL:newURL];
    }
    return self;
}

- (void)dealloc {
    [previewImage release];
    [dateLastUpdated release];
    [url release];
    [super dealloc];
}

- (NSURL *)url {
    return url;
}

- (void)setURL:(NSURL *)newURL {
    [url autorelease];
    url = [newURL copy];
}

- (NSString *)filename {
	id pathComponent = [[[self url] path] lastPathComponent];
	id extension =	[[[self url] path] pathExtension];
	
	if ([pathComponent length] > 10)
		return [[[[pathComponent substringWithRange:NSMakeRange(0, 5)] stringByAppendingString:[@"." stringByAppendingString: extension] ] copy] autorelease];
	else
		return [[pathComponent  copy] autorelease];
}

- (NSString *)localizedTypeDescription {
    NSError *error;
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSString *type = [workspace typeOfFile:[[self url] path] error:&error];
    return type ? [workspace localizedDescriptionForType:type] : @"(Unrecognized file type)";
}

- (NSDate *)dateLastUpdated {
    return dateLastUpdated;
}

- (void)setDateLastUpdated:(NSDate *)newDate {
    id old = dateLastUpdated;
    dateLastUpdated = [newDate copy];
    [old release];
}

- (unsigned long long)fileSize {
    if (fileSize == 0) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *attributes = [fileManager fileAttributesAtPath:[[self url] path] traverseLink:YES];
        fileSize = [[attributes objectForKey:NSFileSize] unsignedLongLongValue];
    }
    return fileSize;
}

- (void)setFileSize:(unsigned long long)newFileSize {
    fileSize = newFileSize;
}

- (NSImage *)previewImage {
    return previewImage;
}

- (void)setPreviewImage:(NSImage *)newPreviewImage {
    if (previewImage != newPreviewImage) {
        [previewImage autorelease];
        previewImage = [newPreviewImage retain];
    }
}

- (BOOL)includedInSlideshow {
    return includedInSlideshow;
}

- (void)setIncludedInSlideshow:(BOOL)flag {
    includedInSlideshow = flag;
}

- (BOOL)loadMetadata {
    // Subclasses should override this.
    return NO;
}

- (BOOL)loadPreviewImage {
    // Subclasses should override this.
    return NO;
}

- (void)loadPreviewImageInBackgroundThread:(id)unusedObject {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [self loadPreviewImage];
    [pool release];
}

- (void)requestPreviewImage {
    if (previewImage == nil) {
        [NSThread detachNewThreadSelector:@selector(loadPreviewImageInBackgroundThread:) toTarget:self withObject:nil];
    }
}

@end
